// document ready

$ = jQuery;
$(function() {
    //var image_path = baseUrl + "/assets/images/connect-" + new_clr + ".png"
    $('.raty').raty({
        starOff: baseUrl + '/assets/raty/images/star-off.png',
        starOn: baseUrl + '/assets/raty/images/star-on.png',
        score: function() {
            return $(this).attr('data-score');
        }
    });

    $(".bxslider li img").elevateZoom({
        zoomWindowFadeIn: 500,
        zoomWindowFadeOut: 500,
        lensFadeIn: 500,
        lensFadeOut: 500
    });


    $('.bxslider').bxSlider({
        pagerCustom: '#bx-pager'
    });

    //    $(".bxslider li img").elevateZoom({zoomWindowPosition: 2});
   
    $('.cart-options .colors span').click(function() {
        var color_val = $(this).attr('id');
        $('.cart-options .product_color').val(color_val);
    });

    if($('.colorbox-html-onClass-relContent')[0])
        $('.colorbox-html-onClass-relContent').click(function(event) {
            event.preventDefault();
            var to_print_html = $('.' + $(this).attr('rel')).html();
            $.colorbox({
                html: to_print_html,
                width: "60%",
                closeButton:true
            //            height: "80%"
            });
        });

    if($('.colorbox-href')[0]){
        $('.colorbox-href').colorbox({
            href: $(this).attr('href'),
            closeButton:true,
            scrolling:true,
            onComplete:function(){
                $('.vertical-scroller').perfectScrollbar('destroy');
    
                $('.vertical-scroller').perfectScrollbar({
                    suppressScrollX: true,
                    includePadding: true
                });
            }
        });
    }

    $('#connect-switch').click(function(event) {
        event.preventDefault();
        
        var current_clr = $(this).attr('rel');
        var new_clr = 'green';

        if (current_clr == 'green')
        {
            new_clr = 'red';
        }
        $(this).attr('rel', new_clr);

        var image_path = baseUrl + "/assets/images/connect-" + new_clr + ".png"
        $(this).find('img').attr('src', image_path);
        
        
        $.ajax({
            url:baseUrl+"/ajax/connect",
            success:function(data){
                window.location.href = window.location.href;
            }
        })
        
    });


    //================= cart button on top ====================================
    $('.display-cart-box').click(function(event) {
        event.preventDefault();
        $('.cart-content-header-onhover').toggleClass('hide');
    });

    //================ search area ===============================================
    $('#header-search-btn').click(function(event) {
        event.preventDefault();
        var thisRel = $(this).attr('rel');
        var images_path = baseUrl + "/assets/images"
        if (thisRel == 'cross')
        {
            $(this).attr('rel', 'no-cross');
            $('#header-search-btn img').attr('src', images_path + "/search-icon.png");
            $('div.search-page').hide();
        }
        else if (thisRel == 'no-cross')
        {
            $(this).attr('rel', 'cross');
            $('#header-search-btn img').attr('src', images_path + "/search-icon-cross.png");
            $('div.search-page').show();
        }
    });

    //========================= whats new brand features =============================
    $('.whats-new').click(function(e) {
        if (!$('#whats-new').hasClass('action')) {

            $(this).animate({
                right: '201px'
            }, "slow", "linear", function() {
                });

            $('#whats-new').animate({
                width: '239px'
            }, "slow", "linear", function() {


                });
            $('#whats-new').addClass('action');
            //$(this).css('right','201px');
            $(".use-scroller").perfectScrollbar('update');
        } else {
            //$(this).css('right','-36px');
            $(this).animate({
                right: '-36px'
            }, "slow", "linear", function() {
                });

            $('#whats-new').animate({
                width: '0px'
            }, "slow", "linear", function() {
                $('#whats-new').removeClass('action');

            });
        }
    });


    //================ home page scroller and css (height 100%) ====================
    var viewportHeight = $('#middle').innerHeight() - 40 - 48;

    $('.use-scroller').height(viewportHeight);

    $('.use-scroller').perfectScrollbar({
        suppressScrollX: true,
        includePadding: true
    });




    //------- products block -------------------------------------------
    var viewportHeight = $('#middle').innerHeight() - 40 - 48;

    
    
    
    //=============isotope masonry=========================
    //----- all product blocks ------------------------------------------
    var _margin = 5 * 2;
    var _padding = 5*2;
    var isotopeHeight = $('.isotope').innerHeight();
    $('.product-grid').height(parseFloat(viewportHeight / 2) - parseFloat(_margin) - 1 );
    
    var _margin = 5 * 2;
    //var _padding = 5*2;
    var _padding = 0;
    var _fbHeight = parseFloat((viewportHeight * 42) / 100);  // Facebook block height -   42%
    var _twHeight = parseFloat((viewportHeight * 23) / 100);  // Twitter block height -   23%
    var _inHeight = parseFloat((viewportHeight * 33) / 100);  // Instagram block height -   33%
    var _yHeight = parseFloat((viewportHeight * 33) / 100);  // Youtube block height -   33%
     
    $('.product-grid.facebook-block').height(_fbHeight - parseFloat(_margin)- parseFloat(_padding)); 
    $('.product-grid.twitter-block').height(_twHeight - parseFloat(_margin)- parseFloat(_padding)); 
    $('.product-grid.instagram-block').height(_inHeight - parseFloat(_margin)- parseFloat(_padding)); 
    $('.product-grid.youtube-block').height(_yHeight - parseFloat(_margin)- parseFloat(_padding)); 


    var $container = $('.isotope');
    $container.isotope({
        itemSelector: '.product-grid',
        layoutMode: 'masonryHorizontal',
        columnWidth: 205,
        isOriginLeft: true,
        //rowHeight:viewportHeight-10,
        rows: 2,
        resizesContainer: false,
        masonry:{
            columnWidth: 205
        //rowHeight:viewportHeight-10
        },
        masonryHorizontal: {
            rowHeight: '.isotope .product-grid.ref'
        }
    });

    
    
    $(window).resize(function(){
        var _margin = 5 * 2;
        var _padding = 5*2;
        var isotopeHeight = $('.isotope').innerHeight();
        $('.product-grid').height(parseFloat(viewportHeight / 2) - parseFloat(_margin) - 1 );
        var $container = $('.isotope');
        $container.isotope('destroy'); // destroy
        
        $container.isotope({
            itemSelector: '.product-grid',
            layoutMode: 'masonryHorizontal',
            columnWidth: 205,
            isOriginLeft: true,
            //rowHeight:viewportHeight-10,
            rows: 2,
            resizesContainer: false,
            masonry:{
                columnWidth: 205
            //rowHeight:viewportHeight-10
            },
            masonryHorizontal: {
                rowHeight: '.isotope .product-grid.ref'
            }
        });
        
    //$('.isotope').width('auto');
    });
    
    $('.isotope').width('auto');
    
    //============= common script for all responsive resizes ================
    //:-Note-: following script will run on load as well as on window resize: :-) Cheers!!
    var resizeScript = function() {
        var viewportHeight = $('#middle').innerHeight() - 40 - 48;
        //--------- diamond block -------------------------------------------
        var _fullHeight = $('.diamond-description-block').height();
        $('.diamond-description-block .upper-part').height(_fullHeight / 10);
        $('.diamond-description-block .lower-part').height(_fullHeight * 9 / 10);

        var _currHeight = _fullHeight * 9 / 10;
        var _offsetTop = 70; //estimated manually -- can be changed later
        $('.description-text').height(_currHeight - _offsetTop);


        //------- brand block -----------------------------------------------
        $('.brand-block').height(parseFloat(viewportHeight - 10) / 3);
        $('.products-scroller').perfectScrollbar('update');

        //-------- sidebar block -------------------------------------------
        var _sidebarHeight = viewportHeight - 37;
        $('.siderbar-middle').height(parseFloat(_sidebarHeight * 30) / 100);
        $('.sidebar-footer').height(parseFloat(_sidebarHeight * 70) / 100);
        var _sidebarmenuParent = $('.sidebar-menu').parent().height();
        //$('.sidebar-menu').height(parseFloat(_sidebarmenuParent*40)/100);
        var _sidebarmenuHeight = 135;

        $('.sidebar-footer .social-block').height(_sidebarmenuParent - _sidebarmenuHeight - 15);
        $(".vertical-scroller").perfectScrollbar('update');
        
        //------- product filter blocks --------------------------------------
        $('.featured-product-slider').height( parseFloat(viewportHeight - 10 - 10)*7/10 );
        //$('.featured-product-slider').width( parseFloat(viewportHeight - 10 - 10)*7/10 );
        $('.featured-product-slider').width(205+205+5);
        $('.featured-product-small').height( parseFloat(viewportHeight - 10 - 10)*3/10 );
    //        var _padding = 0;
    //$container.isotope('bindResize')
    }
    resizeScript();
    $(window).resize(resizeScript);
    
    //=========social isotope
    var $container = $('.social-isotope');
    $container.isotope({
        itemSelector: '.product-grid',
        layoutMode: 'masonryHorizontal',
        columnWidth: 205,
        //rowHeight:viewportHeight-10,
        rows: 2,
        resizesContainer: false,
        masonry:{
            columnWidth: 205
        //rowHeight:viewportHeight-10
        },
        masonryHorizontal: {
            rowHeight: 40
        }
    });
    
    
    var allotedWidth = $('.isotope.social-isotope').width();
    $('.isotope').width($('.isotope').parent('.trends-grid-block').width()-$('.isotope-featured').width()-1);
    //calculate to suit the social isotope width
    //    var socialParent = $('.isotope.social-isotope').closest('.products-scroller').width();
    //    var firstChild = $('.diamond-logo-description').width();
    //    var secondChild = $('.diamond-description-block').width();
    //var allotedWidth = socialParent-firstChild-secondChild;
    
    $('.isotope.social-isotope').width(allotedWidth);
    //============= big blocks isotope ==========================

    var $container = $('.isotope-big');
    $container.isotope({
        itemSelector: '.product-block',
        layoutMode: 'masonryHorizontal',
        columnWidth: 332,
        rows: 1,
        resizesContainer: false
    });
    $('.isotope-big').width('auto');
    //============== brand block isotopes ==========================

    var $container = $('.isotope-brand');


    $container.isotope({
        layoutMode: "perfectMasonry",
        itemSelector: '.brand-block',
        resizesContainer: false,
        perfectMasonry: {
            layout: "horizontal", // Set layout as vertical/horizontal (default: vertical)
            columnWidth: 550, // Set/prefer specific column width (liquid layout tries to prefer said width)
            //rowHeight: 200,          // Set/prefer specific row height (liquid layout tries to prefer said height)

            //liquid: true,            // Set layout as liquid (default: false)
            //cols: 3,                 // Force to have x columns (default: null)
            rows: 3                 // Force to have y rows (default: null)
        }
    });


    //================ product scroller ===========================
    $('.products-scroller').perfectScrollbar({
        suppressScrollY: true,
        includePadding: true
    });

    //=============== product filter page scroller ================
    $('.product-all-scroller').perfectScrollbar({
        suppressScrollY: true,
        includePadding: true
    });

    
    //================ Vertical Scroller ====================
    $('.vertical-scroller').perfectScrollbar({
        suppressScrollX: true,
        includePadding: true
    });

    //================ review box action ======================
    //    $('#write-review').click(function(e) {
    //        $('.popup-review-box').toggleClass('hide');
    //        $('.review-list').toggleClass('hide');
    //    //$('.review-list').toggleClass('hide');
    //    })
    //    
    //=============== flexslider ==============================
    if($('.flexslider')[0])
        $('.flexslider').flexslider({
            animation: "slide",
            directionNav:false
        });

    //============ validate script ======================
    
    if($('.validate-form')[0])
        $('.validate-form').each(function(){
            
            $(this).validate({
                errorClass: "help-block",
                errorElement: "span",
                highlight: function (element, errorClass, validClass) {
                    $(element).closest('.form-group').addClass('has-error');
                },
                unhighlight: function (element, errorClass, validClass) {
                    $(element).closest('.form-group').removeClass('has-error');
                },
                errorPlacement: function (error, element) {
                    if (element.parent('.input-group').length || element.prop('type') === 'checkbox' || element.prop('type') === 'radio') {
                        error.insertAfter(element.parent());
                    } else {
                        error.insertAfter(element);
                    }
                },
                invalidHandler: function(form, validator) {
                    var errors = validator.numberOfInvalids();
                    if (errors) {
                        var message = errors == 1
                        ? 'You missed 1 field. It has been highlighted'
                        : 'You missed ' + errors + ' fields. They have been highlighted';
                        $('#middle').prepend('<p class="bg-danger flashmessenger">'+message+'</p>'); 
                    
                        setTimeout(function() {
                            $('.flashmessenger').fadeOut('slow');
                        }, 3000);

                    
                    }
                }
            
            });
            
        });
        
    //================ Like Action =================
    $('.social-details .like-action').click(function(e){
        e.preventDefault();
        var url = $(this).attr('href');
        var $el = $(this);    
        if($(this).data('likable')){  //logged in
            $.ajax({
                url:url,
                dataType:'json',
                success:function(data){
                    if(data.success){
                        $el.empty().html('Unlike');
                        flashmessenger('success','You really liked that product!');
                        var counts = parseInt($el.prev('.like-counts').html().split(' ')[0])+1;
                        $el.prev('.like-counts').empty().html(counts+' Likes');
                        $el.data('likable',false);
                    }else{
                        flashmessenger('danger',data.message);
                    }
                }
            });
        }else{  
            //not logged in
            if(!$(this).data('logged')){
                //$('#login-link').click();
                window.location.href = baseUrl+'/index/login';
            }
            else{
                
                $.ajax({
                    url:url,
                    dataType:'json',
                    success:function(data){
                        if(data.success){
                            $el.empty().html('Like');
                            flashmessenger('warning','We have variety of products that you may like!');
                        }else{
                            flashmessenger('danger',data.message);
                        }
                    }
                });
                
            }
        }
    })
        
//=============isotope masonry=========================
//    var $container = $('.isotope-featured');
//    $container.isotope({
//        itemSelector: '.product-grid',
//        layoutMode: 'masonryHorizontal',
//        columnWidth: 205,
//        rows: 2,
//        resizesContainer: true,
//        masonry:{
//            columnWidth: 205
//            //rowHeight:viewportHeight-10
//        },
//        masonryHorizontal: {
//            rowHeight: '.featured-product-small'
//        }
//    });
});
